import math
import pyglet
import random
from pyglet.window import key

# Set Size of Window
WinWidth = 640
WinHeight = 480
window = pyglet.window.Window(WinWidth, WinHeight)

GFXbatch = pyglet.graphics.Batch()
background = pyglet.graphics.OrderedGroup(0)
foreground = pyglet.graphics.OrderedGroup(1)
sound = pyglet.resource.media('zap.wav', streaming=False)
start = pyglet.resource.media('start.wav', streaming=False)

class starfield(object):
    def __init__(self, pos , size, max, speed, color):
        self.stars = []
        self.pos = pos
        self.size = size
        self.max = max
        self.speed = speed
        self.color = color

        for loop in range(0, max):
            star = [random.randrange(0, size[0] - 1),
                    random.randrange(0, size[1] - 1)]
            self.stars.append(star)
            
    def draw(self):
        p = []
        c = []
        for loop in range(0, self.max):
            point = (self.pos[0] + self.stars[loop][0], self.pos[1] + self.stars[loop][1] )
            p.extend(point)
            c.extend(self.color)

        batch = pyglet.graphics.Batch()
        
        vertex_list = batch.add(len(p)/2, pyglet.gl.GL_POINTS, None,
            ('v2i', tuple(p)),
            ('c3B', tuple(c)))
        batch.draw()
            
    def update(self, ts):
        for loop in range(0, self.max):
            self.stars[loop][0] += self.speed
            if self.stars[loop][0]>self.size[0]:
                self.stars[loop][0] = 0

# Set up the star fields.
sf = starfield( (10,10), (640,480), 30, 1, (175,175,175))
sf1 = starfield( (10,10), (640,480), 20, 2, (215,215,215))
sf2 = starfield( (10,10), (640,480), 10, 3, (255,255,255))

pyglet.clock.schedule_interval(sf.update,  1/120.0)
pyglet.clock.schedule_interval(sf1.update,  1/120.0)
pyglet.clock.schedule_interval(sf2.update,  1/120.0)


class ship(object):
    def __init__(self):
        ball_image = pyglet.image.load('ship.png')
        self.sprite = pyglet.sprite.Sprite(ball_image, x=50, y=50)
        self.key_handler = key.KeyStateHandler()
        self.bullets = []
        self.reload = 0
    def update(self, ts):
        global GFXbatch, sound
        self.reload +=1
        if self.key_handler[key.LEFT]:
            self.sprite.x -= 4
        if self.key_handler[key.RIGHT]:
            self.sprite.x += 4
        if self.key_handler[key.X] and len(self.bullets)<10 and self.reload>10:
            self.bullets.append(bullet(GFXbatch, (self.sprite.x+25, self.sprite.y+25)))
            sound.play()
            self.reload = 0

    def updateb(self, ts):
        for b in self.bullets:
            b.sprite.y += 8
            if b.sprite.y>480:
                self.removeBullet(b)
    def removeBullet(self, b):
        global GFXbatch
        self.bullets.remove(b)
        b.sprite.delete()

class bullet(object):
    def __init__(self, batch, pos):
        pattern = pyglet.image.SolidColorImagePattern((125, 0, 0, 255))
        image = pyglet.image.create(8, 8, pattern)
        self.sprite = pyglet.sprite.Sprite(img=image,x = pos[0], y = pos[1], batch=batch)

class target(object):
    def __init__(self, batch, pos):
        pattern = pyglet.image.SolidColorImagePattern((0, 125, 0, 255))
        image = pyglet.image.create(64, 64, pattern)
        self.sprite = pyglet.sprite.Sprite(img=image,x = pos[0], y = pos[1], batch=batch)

class Alien(object):
    def __init__(self, batch, pos):
        image =  pyglet.image.load('inv1.png')
        self.sprite = pyglet.sprite.Sprite(img=image,x = pos[0], y = pos[1], batch=batch)
        self.color = (95 + random.randrange(0, 150),0,0)
    def update(self, ts):
        x = self.sprite.x
        y = self.sprite.y
        if x<660:
            x += 4
        else:
            x = -42
            y -= 35
            if y<80: y = 80
        self.sprite.x = x
        self.sprite.y = y
        
# Create text label
#label = pyglet.text.Label('Shoot!', 
#                          font_name='Arial', 
#                          font_size=int(WinHeight/10),
#                          x=window.width//2, y=window.height//2,
#                          anchor_x='center', anchor_y='center',
#                          batch=GFXbatch, group=foreground)
s = ship()
##t = target(GFXbatch, (250, 216))
a = []
for i in range(8):
    a.append(Alien(GFXbatch, (10+(i*60), 430)))
    a.append(Alien(GFXbatch, (10+(i*60), 380)))
    a.append(Alien(GFXbatch, (10+(i*60), 330)))

window.push_handlers(s.key_handler)

# Move on the text along the path
def update(ts):
    global s
    s.update(ts)
    for si in a:
        si.update(ts)
def update2(ts):
    global s,t,a
    s.updateb(ts)
    
    oldbullets = []
    for b in s.bullets[:]:
        hits = [ alien for alien in a if spriteCollision(b.sprite, alien.sprite)]        
        #print hits
        #print a
        if len(hits)>0:
            oldbullets.append(b)
            for h in hits:
                h.sprite.delete()
                a.remove(h)
            s.removeBullet(b)
        #if spriteCollision(b.sprite, alien.sprite):
        #s.removeBullet(b)
        #alien.sprite.delete()
        #a.remove(alien)    
    return
    #for b in s.bullets:
    #    if spriteCollision(b.sprite, t.sprite):
    #        t.sprite.y += 10
    #        if t.sprite.y>480: t.sprite.y=100
    #        s.removeBullet(b)

def spriteCollision(sprite1, sprite2):
    br = (sprite1.x, sprite1.y, sprite1.x + sprite1.width, sprite1.y + sprite1.height)
    tr = (sprite2.x, sprite2.y, sprite2.x + sprite2.width, sprite2.y + sprite2.height)
    return collision(br,tr)
    
def collision(rect1, rect2):
    if not(rect1[0]>rect2[2] or rect2[0]>rect1[2] or rect1[1]>rect2[3] or rect2[1]>rect1[3]):
        return True
    else:
        return False
        
pyglet.clock.schedule_interval(update,  1/100.0)
pyglet.clock.schedule_interval(update2,  1/200.0)

@window.event
def on_draw():
    global GFXbatch
    window.clear()
    sf.draw()
    sf1.draw()
    sf2.draw()
    GFXbatch.draw()
    s.sprite.draw()

start.play()
pyglet.app.run()

